﻿package com.moonshineproject.plugin.dragdrop {
	import com.moonshineproject.IDEModel;
	import com.moonshineproject.events.OpenFileEvent;
	import com.moonshineproject.plugin.PluginBase;
	import com.moonshineproject.plugin.project.event.ProjectEvent;
	import com.moonshineproject.plugin.project.vo.ProjectVO;
	import com.moonshineproject.plugin.settings.vo.ISetting;
	import com.moonshineproject.view.MainView;
	
	import flash.desktop.Clipboard;
	import flash.desktop.ClipboardFormats;
	import flash.desktop.NativeDragManager;
	import flash.events.NativeDragEvent;
	import flash.filesystem.File;

	public class DragDropPlugin extends PluginBase 
	{
		override public function get name():String 			{return "Drag and Drop Plugin";}
		override public function get author():String 		{return "Moonshine Project Team";}
		override public function get description():String 	{return "Adds operating system drag and drop support.";}
		
		private var mainView:MainView;
		
	
		public function getSettingsList():Vector.<ISetting>	{ return new Vector.<ISetting>(); }
		
		override public function activate():void
		{
			mainView = IDEModel.getInstance().mainView;
			mainView.addEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, dragEnter);
			mainView.addEventListener(NativeDragEvent.NATIVE_DRAG_DROP, dragDrop);
			
			super.activate(); 	
		}
		
		override public function deactivate():void
		{
			if(!mainView){			
				mainView.removeEventListener(NativeDragEvent.NATIVE_DRAG_ENTER, dragEnter);
				mainView.removeEventListener(NativeDragEvent.NATIVE_DRAG_DROP, dragDrop);
				mainView = null;
			}
			
			super.deactivate(); 	
		}
		
		
		private function dragEnter(e:NativeDragEvent):void 
		{
			var cb:Clipboard = e.clipboard;
			if (cb.hasFormat(ClipboardFormats.FILE_LIST_FORMAT)) 
			{
				NativeDragManager.acceptDragDrop(mainView);
			}
		}
		
		
		private function dragDrop(e:NativeDragEvent):void 
		{
			var cb:Clipboard = e.clipboard;
			if (cb.hasFormat(ClipboardFormats.FILE_LIST_FORMAT)) 
			{
				var files:Vector.<File> = Vector.<File>(cb.getData(ClipboardFormats.FILE_LIST_FORMAT));
				for (var i:int = 0; i < files.length; i++) 
				{
					var file:File = files[i];
					if (file.isDirectory)
					{
						// TODO: Search for project files in directory?
						dispatcher.dispatchEvent(
							new ProjectEvent(ProjectEvent.ADD_PROJECT, new ProjectVO(file))
						);
					}
					else
					{
						dispatcher.dispatchEvent(
							new OpenFileEvent(OpenFileEvent.OPEN_FILE, files[i])
						);
					}
				}
			}
		}
		
	}
}